import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';
import {
  APP_INITIALIZER,
  DEFAULT_CURRENCY_CODE,
  LOCALE_ID,
  ModuleWithProviders,
  NgModule,
  Optional,
  SkipSelf
} from '@angular/core';

import { LockScreenAppInitializer, ThemeAppInitializer } from '@core/base';
import { throwIfAlreadyLoaded } from '@core/module-import-guard';
import { environment } from '@env/environment';
import { KeycloakService } from 'keycloak-angular';
import { NzConfig, NZ_CONFIG } from 'ng-zorro-antd/core/config';
import { NZ_I18N, zh_CN } from 'ng-zorro-antd/i18n';

registerLocaleData(zh);

// NG-ZORRO 全局配置项
const ngZorroConfig: NzConfig = {
  pageHeader: { nzGhost: false }
};

const appInitProvides = [
  ThemeAppInitializer,
  LockScreenAppInitializer,
  {
    provide: APP_INITIALIZER,
    useFactory: environment.initializeKeycloak,
    multi: true,
    deps: [KeycloakService]
  },
  { provide: NZ_CONFIG, useValue: ngZorroConfig },
  { provide: DEFAULT_CURRENCY_CODE, useValue: 'CNY' },
  { provide: NZ_I18N, useValue: zh_CN },
  { provide: LOCALE_ID, useValue: 'zh' }
];

@NgModule({
  imports: []
})
export class ConfigModule {
  constructor(@Optional() @SkipSelf() parentModule: ConfigModule) {
    throwIfAlreadyLoaded(parentModule, 'ConfigModule');
  }

  static forRoot(): ModuleWithProviders<ConfigModule> {
    return {
      ngModule: ConfigModule,
      providers: [...appInitProvides]
    };
  }
}
